<template>
  <div id="appDetailPage">
    <a-card>
      <a-row style="margin-bottom: 16px">
        <a-col flex="auto" class="content-wrapper">
          <h2>{{ data.appName }}</h2>
          <p>{{ data.appDesc }}</p>
          <p>应用类型：{{ APP_TYPE_MAP[data.appType] }}</p>
          <p>评分策略：{{ APP_SCORING_STRATEGY_MAP[data.scoringStrategy] }}</p>
          <p>
            <a-space>
              作者：
              <div :style="{ display: 'flex', alignItems: 'center' }">
                <a-avatar
                  :size="24"
                  :image-url="data.user?.userAvatar"
                  :style="{ marginRight: '8px' }"
                />
                <a-typography-text
                  >{{ data.user?.userName ?? "无名" }}
                </a-typography-text>
              </div>
            </a-space>
          </p>
          <p>
            创建时间：{{ dayjs(data.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </p>
          <a-space size="medium">
            <a-button type="primary" :href="`/answer/do/${id}`"
              >开始答题
            </a-button>
            <a-button @click="doShare">分享应用</a-button>
            <a-button v-if="isMy" :href="`/add/question/${id}`"
              >设置题目
            </a-button>
            <a-button v-if="isMy" :href="`/add/scoring_result/${id}`"
              >设置评分
            </a-button>
            <a-button v-if="isMy" :href="`/add/app/${id}`">修改应用</a-button>
            <a-button @click="lookComments">写评论</a-button>
          </a-space>
        </a-col>
        <a-col flex="320px">
          <a-image width="100%" :src="data.appIcon" />
        </a-col>
      </a-row>
    </a-card>
    <!-- <h3>评论区</h3>-->
    <a-card
      id="CommentInfo"
      v-if="commentState"
      :bordered="false"
      class="comment-card"
    >
      <!--添加评论模块-->
      <div class="comment-header">
        <span class="comment-title">
          <icon-message />
          用户评论区
        </span>
        <a-tag color="arcoblue">{{ dataSource.length }} 条评论</a-tag>
      </div>

      <a-divider style="margin: 16px 0" />

      <div class="add-comment-section">
        <div class="user-info-header">
          <a-avatar
            :size="40"
            :image-url="loginUserStore.loginUser?.userAvatar"
            :style="{ backgroundColor: '#3370ff' }"
          >
            {{ getUserInitial(loginUserStore.loginUser?.userName) }}
          </a-avatar>
          <span class="comment-as"
            >评论者: {{ loginUserStore.loginUser?.userName || "游客" }}</span
          >
        </div>

        <a-textarea
          v-model="commentContentTop"
          placeholder="分享你的想法..."
          :style="{ width: '100%', marginTop: '16px', borderRadius: '4px' }"
          :auto-size="{ minRows: 3, maxRows: 6 }"
          :max-length="1000"
          show-word-limit
        />
        <div class="comment-action">
          <a-space>
            <a-button @click="doClearCommentForm('top')"> 重置 </a-button>
            <a-button
              type="primary"
              status="success"
              @click="doSubmitCommentTop"
              :loading="loadingSubmitTop"
            >
              发表评论
            </a-button>
          </a-space>
        </div>
      </div>

      <a-divider style="margin: 24px 0" />

      <!--评论列表模块-->
      <div class="comment-list-section">
        <h3 class="comment-section-title">全部评论</h3>
        <a-list
          class="list-demo-action-layout aListDataItem"
          :bordered="false"
          :data="dataSource"
          :pagination-props="paginationProps"
          :loading="loadingList"
        >
          <template #item="{ item }">
            <a-list-item class="comment-list-item">
              <a-comment
                :author="item.senderName"
                :datetime="dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')"
              >
                <template #content>
                  <div class="comment-content">
                    <MdViewer :value="item.comment"></MdViewer>
                  </div>
                </template>
                <template #actions>
                  <div class="comment-actions">
                    <span
                      class="action-btn"
                      key="reply"
                      @click="doShowReply('add', item)"
                      v-if="item.senderId !== loginUserId"
                    >
                      <icon-reply /> 回复
                    </span>
                    <span
                      class="action-btn"
                      key="edit"
                      v-if="
                        loginUserStore.loginUser.userRole ===
                          ACCESS_ENUM.ADMIN || item.senderId === loginUserId
                      "
                      @click="doShowReply('edit', item)"
                    >
                      <icon-edit /> 编辑
                    </span>
                    <a-popconfirm
                      content="确定要删除吗?"
                      type="warning"
                      :onOk="() => deleteComment(item)"
                      v-if="
                        loginUserStore.loginUser.userRole ===
                          ACCESS_ENUM.ADMIN || item.senderId === loginUserId
                      "
                    >
                      <span class="action-btn delete-btn">
                        <icon-delete /> 删除
                      </span>
                    </a-popconfirm>
                  </div>
                </template>
                <template #avatar>
                  <a-avatar
                    :size="40"
                    :image-url="item.senderAvatar"
                    :style="{ backgroundColor: '#3370ff' }"
                  >
                    {{ getUserInitial(item.senderName) }}
                  </a-avatar>
                </template>
                <a-comment
                  align="right"
                  class="reply-comment"
                  :avatar="loginUserStore.loginUser.userAvatar"
                  v-if="showReply && activeId === item.id"
                >
                  <template #actions>
                    <a-space>
                      <a-button key="0" @click="doClearCommentForm('bottom')">
                        取消
                      </a-button>
                      <a-button
                        key="1"
                        type="primary"
                        :loading="loadingSubmitBottom"
                        @click="doSubmitCommentBottom(item)"
                      >
                        {{ curOp === "add" ? "发表回复" : "保存编辑" }}
                      </a-button>
                    </a-space>
                  </template>
                  <template #content>
                    <a-textarea
                      v-model="commentContentBottom"
                      placeholder="写下你的回复..."
                      :auto-size="{ minRows: 2, maxRows: 4 }"
                      show-word-limit
                      :max-length="500"
                    />
                  </template>
                </a-comment>
                <a-collapse
                  v-if="item.children && item.children.length > 0"
                  expand-icon-position="left"
                  :show-expand-icon="true"
                  :bordered="false"
                  class="comment-replies"
                >
                  <template #expand-icon>
                    <span class="action-btn" key="show">
                      <icon-message />
                    </span>
                  </template>
                  <a-collapse-item>
                    <template #header>
                      <span class="replies-count">
                        {{ item.children?.length }} 条回复
                      </span>
                    </template>
                    <div class="replies-container">
                      <div
                        v-for="(sonItem, index) in item.children"
                        :key="index"
                        class="reply-item"
                      >
                        <a-comment
                          :author="sonItem.senderName"
                          :datetime="
                            dayjs(sonItem.createTime).format(
                              'YYYY-MM-DD HH:mm:ss'
                            )
                          "
                        >
                          <template #content>
                            <div class="comment-content sub-comment">
                              <MdViewer :value="sonItem.comment"></MdViewer>
                            </div>
                          </template>
                          <template #actions>
                            <div class="comment-actions">
                              <span
                                class="action-btn"
                                key="edit"
                                @click="
                                  () => {
                                    showReplySon = !showReplySon;
                                    showReplySonText = sonItem.comment;
                                    activeId = sonItem.id;
                                  }
                                "
                                v-if="
                                  loginUserStore.loginUser.userRole ===
                                    ACCESS_ENUM.ADMIN ||
                                  sonItem.senderId === loginUserId
                                "
                              >
                                <icon-edit /> 编辑
                              </span>
                              <a-popconfirm
                                content="确定要删除吗?"
                                type="warning"
                                :onOk="() => deleteComment(sonItem)"
                                v-if="
                                  loginUserStore.loginUser.userRole ===
                                    ACCESS_ENUM.ADMIN ||
                                  sonItem.senderId === loginUserId
                                "
                              >
                                <span class="action-btn delete-btn">
                                  <icon-delete /> 删除
                                </span>
                              </a-popconfirm>
                            </div>
                          </template>
                          <template #avatar>
                            <a-avatar
                              :size="36"
                              :image-url="sonItem.senderAvatar"
                              :style="{ backgroundColor: '#3370ff' }"
                            >
                              {{ getUserInitial(sonItem.senderName) }}
                            </a-avatar>
                          </template>
                          <a-comment
                            align="right"
                            class="reply-comment"
                            :avatar="loginUserStore.loginUser.userAvatar"
                            v-if="showReplySon && activeId === sonItem.id"
                          >
                            <template #actions>
                              <a-space>
                                <a-button
                                  key="0"
                                  @click="
                                    () => {
                                      showReplySon = false;
                                    }
                                  "
                                >
                                  取消
                                </a-button>
                                <a-button
                                  key="1"
                                  type="primary"
                                  :loading="loadingSubmitBottom"
                                  @click="editComment(sonItem)"
                                >
                                  保存编辑
                                </a-button>
                              </a-space>
                            </template>
                            <template #content>
                              <a-textarea
                                v-model="showReplySonText"
                                placeholder="编辑你的评论..."
                                :auto-size="{ minRows: 2, maxRows: 4 }"
                                show-word-limit
                                :max-length="500"
                              />
                            </template>
                          </a-comment>
                        </a-comment>
                      </div>
                    </div>
                  </a-collapse-item>
                </a-collapse>
              </a-comment>
            </a-list-item>
          </template>
          <template #empty>
            <div class="comment-empty">
              <icon-message
                :size="48"
                :style="{ color: 'var(--color-text-3)' }"
              />
              <p>暂无评论，快来抢沙发吧！</p>
            </div>
          </template>
        </a-list>
      </div>
    </a-card>
    <ShareModal :link="shareLink" title="应用分享" ref="shareModalRef" />
  </div>
</template>

<script setup lang="ts">
import { computed, defineProps, ref, watchEffect, withDefaults } from "vue";
import API from "@/api";
import { getAppVoByIdUsingGet } from "@/api/appController";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import { useLoginUserStore } from "@/store/userStore";
import { APP_SCORING_STRATEGY_MAP, APP_TYPE_MAP } from "@/constant/app";
import ShareModal from "@/components/ShareModal.vue";
import {
  deleteCommentUsingDelete,
  editCommentUsingPut,
  listAllUsingPost,
  replyCommentUsingPost,
} from "@/api/appCommentController";
import ACCESS_ENUM from "@/access/accessEnum";
import MdEditor from "@/components/MdEditor.vue";
import MdViewer from "@/components/MdViewer.vue";

/**
 * loading等状态
 */
const loadingList = ref(false);
const loadingSubmit = ref(false);

const activeId = ref(0);
const commentState = ref(false);
const commentContentTop = ref("");
const commentContentBottom = ref("");
const onContentChange = (value: string) => {
  commentContentTop.value = value;
};

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => {
    return "";
  },
});
const solution = ref({});
const router = useRouter();

const data = ref<API.AppVO>({});

// 获取登录用户
const loginUserStore = useLoginUserStore();
let loginUserId = loginUserStore.loginUser?.id;
// 是否为本人创建
const isMy = computed(() => {
  return loginUserId && loginUserId === data.value.userId;
});

/**
 * 获取用户名首字母（用于头像显示）
 */
const getUserInitial = (userName: string | undefined) => {
  if (!userName) return "?";
  return userName.charAt(0).toUpperCase();
};

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.id) {
    return;
  }
  const res = await getAppVoByIdUsingGet({
    id: props.id as any,
  });
  if (res.data.code === 0) {
    data.value = res.data.data as any;
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  loadData();
});

// 分享弹窗的引用
const shareModalRef = ref();

// 分享链接
const shareLink = `${window.location.protocol}//${window.location.host}/app/detail/${props.id}`;

// 分享
const doShare = (e: Event) => {
  if (shareModalRef.value) {
    shareModalRef.value.openModal();
  }
  // 阻止冒泡，防止跳转到详情页
  e.stopPropagation();
};

const dataSource = ref<any[]>([]);

const lookComments = async (key: any) => {
  if (commentState.value) {
    commentState.value = false;
    return;
  }
  commentState.value = true;
  if (dataSource.value.length == 0) {
    loadCommentData({
      ifMerge: true,
      articleId: props.id as any,
      sortField: "createTime",
      sortOrder: "ascend",
    } as API.ArticleCommentQueryRequest);
  }
};

const paginationProps = ref({
  page: 5,
  total: dataSource.value.length,
  showTotal: true,
});

const loadCommentData = async (item: API.ArticleCommentQueryRequest) => {
  loadingList.value = true;
  const res = await listAllUsingPost(item);
  console.log(res);
  loadingList.value = false;
  if (res.data.code === 0) {
    dataSource.value = res.data.data || [];
    paginationProps.value.total = dataSource.value.length;
  } else {
    message.error("评论数据加载失败", res.data.message || "");
  }
};
const loadingSubmitTop = ref(false);
const loadingSubmitBottom = ref(false);
const doSubmitCommentTop = async () => {
  const text = commentContentTop.value;
  if (text == null || text.trim() === "") {
    message.error("评论内容不能为空！");
    return;
  }
  // 新增评论
  loadingSubmitTop.value = true;
  const res = await replyCommentUsingPost({
    articleId: props.id as any,
    senderId: loginUserId,
    senderName: loginUserStore.loginUser.userName,
    senderAvatar: loginUserStore.loginUser.userAvatar,
    comment: text,
    receiverId: undefined,
  });
  loadingSubmitTop.value = false;
  if (res.data.code === 0) {
    message.success(res.data.message || "评论成功");
  } else {
    message.error("评论失败，" + (res.data.message || ""));
  }
  loadCommentData({
    articleId: props.id as any,
    ifMerge: true,
    sortField: "createTime",
    sortOrder: "ascend",
  } as API.ArticleCommentQueryRequest);
};

const showReply = ref(false);
const doShowReply = (opType: string, item: API.AppComment) => {
  activeId.value = item.id as any;
  showReply.value = !showReply.value;
  curOp.value = opType;
  if (opType === "edit") {
    commentContentBottom.value = item.comment as any;
  }
};

const curOp = ref("add");
const doSubmitCommentBottom = async (item: API.AppComment) => {
  const text = commentContentBottom.value;
  if (text == null || text.trim() === "") {
    message.error("评论内容不能为空！");
    return;
  }
  loadingSubmitBottom.value = true;
  if (curOp.value === "add") {
    const res = await replyCommentUsingPost({
      receiverId: item.senderId,
      articleId: props.id as any,
      senderId: loginUserId,
      senderName: loginUserStore.loginUser.userName,
      senderAvatar: loginUserStore.loginUser.userAvatar,
      comment: text,
    });
    loadingSubmitBottom.value = false;
    if (res.data.code === 0) {
      commentContentBottom.value = "";
      message.success(res.data.message || "回复成功");
      showReply.value = false;
      loadCommentData({
        ifMerge: true,
        articleId: props.id as any,
        sortField: "createTime",
        sortOrder: "ascend",
      } as API.ArticleCommentQueryRequest);
    } else {
      message.error("回复失败！" + (res.data.message || ""));
    }
  } else {
    const res = await editCommentUsingPut({
      id: item.id,
      senderId: item.senderId,
      comment: text,
    });
    loadingSubmitBottom.value = false;
    if (res.data.code === 0) {
      commentContentBottom.value = "";
      message.success(res.data.message || "编辑成功");
      showReply.value = false;
      loadCommentData({
        ifMerge: true,
        articleId: props.id as any,
        sortField: "createTime",
        sortOrder: "ascend",
      } as API.ArticleCommentQueryRequest);
    } else {
      message.error("编辑失败！" + (res.data.message || ""));
    }
  }
};

const editComment = async (item: API.AppComment) => {
  // 判空
  if (showReplySonText.value == null || showReplySonText.value.trim() === "") {
    message.error("回复内容不能为空！");
    return;
  }
  // 根据id修改
  loadingSubmitBottom.value = true;
  const res = await editCommentUsingPut({
    id: item.id,
    comment: showReplySonText.value as any,
  });
  loadingSubmitBottom.value = false;
  if (res.data.code === 0) {
    message.success(res.data.message || "编辑成功");
    showReplySon.value = false;
    loadCommentData({
      ifMerge: true,
      articleId: props.id as any,
      sortField: "createTime",
      sortOrder: "ascend",
    } as API.ArticleCommentQueryRequest);
  } else {
    message.error("编辑失败！" + (res.data.message || ""));
  }
  return;
};

const doClearCommentForm = (type: string) => {
  if (type === "top") {
    commentContentTop.value = "";
    return;
  }
  commentContentBottom.value = "";
  doShowReply("add", undefined as any);
};

const showReplySon = ref(false);
const showReplySonText = ref("");

const deleteComment = async (item: API.AppComment) => {
  if (!item) {
    message.error("删除失败！");
    return;
  }
  const res = await deleteCommentUsingDelete(item);
  if (res.data.code === 0) {
    message.success("删除成功！");
    loadCommentData({
      ifMerge: true,
      articleId: props.id as any,
      sortField: "createTime",
      sortOrder: "ascend",
    } as API.ArticleCommentQueryRequest);
  } else {
    message.error("删除失败！" + (res.data.message || ""));
  }
};
</script>

<style scoped>
#appDetailPage {
  margin: 0 auto;
}

#appDetailPage .content-wrapper > * {
  margin-bottom: 24px;
}

.arco-input-wrapper,
.arco-input-tag {
  width: 63%;
}

/* 评论区样式 */
.comment-card {
  margin-top: 24px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.comment-title {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.add-comment-section {
  background-color: var(--color-fill-2);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}

.user-info-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.comment-as {
  font-size: 14px;
  color: var(--color-text-2);
}

.comment-action {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.comment-section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: var(--color-text-1);
}

.comment-list-item {
  border-bottom: 1px solid var(--color-border-2);
  padding: 16px 0;
}

.comment-content {
  background-color: var(--color-fill-2);
  padding: 12px;
  border-radius: 8px;
  margin: 8px 0;
}

.sub-comment {
  background-color: var(--color-fill-1);
}

.comment-actions {
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

.action-btn {
  font-size: 14px;
  color: var(--color-text-3);
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  transition: color 0.2s;
}

.action-btn:hover {
  color: var(--color-primary-6);
}

.delete-btn:hover {
  color: var(--color-danger-6);
}

.reply-comment {
  background-color: var(--color-fill-1);
  border-radius: 8px;
  padding: 12px;
  margin-top: 12px;
}

.comment-replies {
  margin-top: 12px;
}

.replies-count {
  font-size: 14px;
  color: var(--color-text-3);
}

.replies-container {
  padding-left: 24px;
}

.reply-item {
  padding: 12px 0;
  border-bottom: 1px dashed var(--color-border-2);
}

.reply-item:last-child {
  border-bottom: none;
}

.comment-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  color: var(--color-text-3);
}

.comment-empty p {
  margin-top: 16px;
  font-size: 16px;
}
</style>
